package com.taotao.cart.service;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.abel533.entity.Example;
import com.taotao.cart.bean.Item;
import com.taotao.cart.bean.TbUser;
import com.taotao.cart.mapper.CartMapper;
import com.taotao.cart.pojo.Cart;
import com.taotao.cart.threadlocal.UserThreadLocal;

@Service
public class CartService {

	@Autowired
	private CartMapper cartMapper;
	
	@Autowired
	private ItemService itemService;
	
	/**
	 * 添加商品到购物车上
	 * 逻辑：判断加入商品在购物车中是否存在，如果存在则数量相加，如果不存在，直接写入
	 * <p>Title: addItemToCart</p>
	 * <p>Description: </p>
	 * @param itemId
	 */
	public void addItemToCart(Long itemId,Integer num) {
		TbUser user = UserThreadLocal.get();
		Cart record = new Cart();
		record.setItemId(itemId);
		record.setUserId(user.getId());
		Cart cart = this.cartMapper.selectOne(record);
		
		if(cart == null) {
			cart = new Cart();
			cart.setCreated(new Date());
			cart.setItemId(itemId);
			cart.setNum(num);
			Item item = this.itemService.getItemById(itemId);
			
			cart.setItemPrice(item.getPrice());
			cart.setUserId(user.getId());
			cart.setUpdated(cart.getCreated());
			cart.setItemTitle(item.getTitle());
			cart.setItemImage(StringUtils.split(item.getImage(), ",")[0]);
			this.cartMapper.insert(cart);
		}else {
			cart.setNum(cart.getNum() + num);
			cart.setUpdated(new Date());
			cartMapper.updateByPrimaryKeySelective(cart);
		}
		
		
	}
	
	public List<Cart> queryCartList() {
		return this.queryCartList(UserThreadLocal.get().getId());
	}
	
	public List<Cart> queryCartList(Long userId) {
		Example example = new Example(Cart.class);
		example.setOrderByClause("CREATED DESC");
		example.createCriteria().andEqualTo("userId", userId);
		
		return this.cartMapper.selectByExample(example);
	}
	
	public void updateNum(Long itemId, Integer num) {
		// 更新条件
		Example example = new Example(Cart.class);
		example.createCriteria().andEqualTo("userId", UserThreadLocal.get().getId()).andEqualTo("itemId", itemId);

		// 更新的内容
		Cart record = new Cart();
		record.setNum(num);
		record.setUpdated(new Date());

		// 执行更新
		this.cartMapper.updateByExampleSelective(record, example);
	}

	public void deleteItem(Long itemId) {
		// 实现物理删除
		Cart record = new Cart();
		record.setItemId(itemId);
		record.setUserId(UserThreadLocal.get().getId());
		this.cartMapper.delete(record);
	}
}
